package com.ikkong.biz.service.impl;

import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.ikkong.biz.BizCst;
import com.ikkong.biz.model.Teacher;
import com.ikkong.core.base.service.impl.BaseService;
import com.ikkong.biz.model.Notice;
import com.ikkong.biz.service.NoticeService;
import com.ikkong.core.dao.Blade;
import com.ikkong.core.dao.Db;
import com.ikkong.core.jfinal.ext.kit.JStrKit;
import com.ikkong.core.jfinal.ext.shiro.ShiroKit;
import com.ikkong.core.toolbox.Conver;
import com.ikkong.core.toolbox.Record;
import com.ikkong.core.toolbox.kit.CollectionKit;
import com.ikkong.qy.util.WeixinApi;
import com.jfinal.kit.StrKit;

import java.util.*;

/**
 * Generated by Blade.
 * 2016-11-21 18:00:39
 */
public class NoticeServiceImpl extends BaseService<Notice> implements NoticeService{

    @Override
    public List<Record> getStuNoticeTree() {
        List<Record> resList = new ArrayList<>();
        List<Record> studentDeptList = Db.init().selectList("select d.id,d.simplename as name,d.pId from tfw_dept d,tb_auth_tag at,tb_teacher t2 where t2.id =#{userid} and t2.notice_tag_id = at.id and at.student_auth like concat('%,',d.id,',%') and d.type = 3 group by d.id order by d.id asc",
                Record.create().set("userid", 2001));
        if(studentDeptList != null && studentDeptList.size() > 0){
            Record temp = Record.create();
            temp.put("id", 1001);
            temp.put("name", "所有学生");
            temp.put("pId", 1);
            temp.put("open",true);
            resList.add(temp);
            resList.addAll(studentDeptList);
        }

        return resList;
    }

    @Override
    public List<Record> getParNoticeTree() {
        List<Record> resList = new ArrayList<>();

        List<Record> parentDeptList = Db.init().selectList("select d.id,d.simplename as name,d.pId from tfw_dept d,tb_auth_tag at,tb_teacher t2 where t2.id =#{userid} and t2.notice_tag_id = at.id and at.parent_auth like concat('%,',d.id,',%') and d.type = 2 group by d.id order by d.id asc",
                Record.create().set("userid", 2001));

        if(parentDeptList != null && parentDeptList.size() > 0){
            Record temp = Record.create();
            temp.put("id", 1002);
            temp.put("name", "所有家长");
            temp.put("open",true);
            temp.put("pId", 1);
            resList.add(temp);
            resList.addAll(parentDeptList);
        }
        return resList;
    }

    @Override
    public List<Record> getTeaNoticeTree() {
        List<Record> teacherDeptList = Db.init().selectList("select d.id,d.simplename as name,d.pId,'true' as open from tfw_dept d,tb_teacher t1,tb_auth_tag at,tb_teacher t2 where t2.id =#{userid} and t2.notice_tag_id = at.id and at.teacher_auth like concat('%,',t1.id,',%') and t1.depts like concat('%,',d.id,',%') and d.type = 1 group by d.id order by d.id asc",
                Record.create().set("userid", 2001));
        List<Record> teacherList = Db.init().selectList("select t1.id,t1.name,t1.depts as pId from tb_teacher t1,tb_auth_tag at,tb_teacher t2 where t2.id =#{userid} and t2.notice_tag_id = at.id and at.teacher_auth like concat('%,',t1.id,',%') group by t1.id order by t1.id asc",
                Record.create().set("userid", 2001));

        List<Record> maps = new ArrayList<>();
        for (Map m:teacherList ) {
            String depts = m.get("pId")!=null?m.get("pId").toString():null;
            if (JStrKit.notBlank(depts)){  //存在部门，拆分depts ,12,12,11,记录为三条
                String[] ss = depts.split(",");
                for (String s : ss) {
                    if(StrKit.notBlank(s)){
                        Map map = Maps.newHashMap();
                        map.put("id",m.get("id"));
                        map.put("pId", Conver.toInt(s,null));
                        map.put("name",m.get("name"));
                        map.put("leaf",true);
                        maps.add(Record.parse(map));
                    }
                }
            }else {  //未分配部门的全部挂在顶级节点下面
                Map map = Maps.newHashMap();
                map.put("id",m.get("id"));
                map.put("pId", 1003);
                map.put("name",m.get("name"));
                map.put("leaf",true);
                maps.add(Record.parse(map));
            }
        }

        List<Record> resList = new ArrayList<>();
        resList.addAll(teacherDeptList);
        resList.addAll(maps);
        return resList;
    }

    @Override
    public boolean doSend(Notice notice) {

        int teacherId = ShiroKit.getUser().getTeacherId();
        Teacher user = Blade.create(Teacher.class).findById(teacherId);
        //TODO 测试用，到时再改 ,这个是用来给超级管理员用的
        if (user == null ){
            user = (Teacher) ShiroKit.getSession().getAttribute(BizCst.SESSION_TEACHER);
        }

        notice.setCname(user.getName());
        notice.setCreator(teacherId);
        notice.setCtime(new Date());
        notice.setVersion(0);

        int id = Blade.create(Notice.class).saveRtId(notice);

        if(id > 0){
        	notice.setId(id);
            String teaIds = notice.getTeacher_auth();
            String parIds = notice.getParent_auth();
            String stuIds = notice.getStudent_auth();
            if(JStrKit.notBlank(teaIds)){
                Set<Integer> set = Sets.newHashSet();
                for (String s: teaIds.split(",")
                     ) {
                    int t = Integer.parseInt(s,10);
                    if(t<10000){
                    	List<Integer> list = Db.init().queryListInt("select id from tb_teacher where find_in_set("+t+",depts)", null);
                    	set.addAll(list);
                    }else{
                    	set.add(t);
                    }
                }
                teaIds = CollectionKit.join(set,",");
                Blade.dao().executeUpdate("call create_notice('"+teaIds+"',1,"+id+","+teacherId+",'"+user.getName()+"','"+notice.getTitle()+"');", null);
            }
            if(JStrKit.notBlank(parIds)){
                Blade.dao().executeUpdate("call create_notice('"+parIds+"',2,"+id+","+teacherId+",'"+user.getName()+"','"+notice.getTitle()+"');", null);
            }
            if(JStrKit.notBlank(stuIds)){
                Blade.dao().executeUpdate("call create_notice('"+stuIds+"',3,"+id+","+teacherId+",'"+user.getName()+"','"+notice.getTitle()+"');", null);
            }
            WeixinApi.pushNotice(notice);
            return true;
        }
        return false;
    }

	@Override
	public int getUnRead() {
		Map<String,Object> map = Maps.newHashMap();
		map.put("customer_id",ShiroKit.getTeacher().getId());
		return Db.init().queryInt("select count(1) from tb_notice_result t where t.customer_id=#{customer_id} and t.is_read=0", map);
	}
}
